package wx.controls
{
	import flash.display.DisplayObject;
	import flash.events.MouseEvent;
	
	import wx.core.ITheme;
	import wx.core.SettingCache;

	/**
	 * 
	 * @author wujianqi
	 * 复选控件
	 * 
	 */	
	public class Checkbox extends ButtonBase
	{
		private var _selected:Boolean = false;
		private var _text:String;
		private var _label:Label;
		
		public var value:Object;		
		
		private const _theme:ITheme = SettingCache.theme;
		
		public function Checkbox($label:String)
		{
			var up:DisplayObject =  _theme.checkboxNormalSkin;
			var hover:DisplayObject = _theme.checkboxHoverSkin;
			var down:DisplayObject =_theme.checkboxDownSkin;
			var disabled:DisplayObject = _theme.checkboxDisableSkin;
			super(up,hover,down,disabled);
			
			_text = $label;		
			addLabel();
			if(_enable) bindEvent();
		}
		
		private function onMouseClick(e:MouseEvent):void{
			this.selected = _selected?false:true;
		}
		private function bindEvent():void{
			addEventListener(MouseEvent.CLICK,onMouseClick);
		}
		
		private function unbindEvent():void{
			removeEventListener(MouseEvent.CLICK,onMouseClick);
		}

		public function get label():String
		{
			return _text;
		}
		
		public function set label(value:String):void
		{
			if(_text != value){
				_text = value;
				updateDisplay();
			}
		}
		
		public function get selected():Boolean
		{
			return _selected;
		}
		
		public function set selected(value:Boolean):void
		{
			if(_selected != value){
				_selected = value;
				super.upSkin = _selected?_theme.checkboxSelectedSkin:_theme.checkboxNormalSkin;
				super.hoverSkin =  _selected?_theme.checkboxSelectedHoverSkin:_theme.checkboxHoverSkin;
				super.updateState();
			}
		}
		
		override public function set enable(value:Boolean):void{
			if(_enable != value){
				super.enable = value;
				if(!_enable) unbindEvent();
				else bindEvent();
			}			
		}
		
		private  function updateDisplay():void
		{
			if(contains(_label)){
				removeChild(_label);
				addLabel();
			}
		}
		
		private function addLabel():void{
			var w:Number = this.width;
			var h:Number = this.height;
			_label = new Label(_text);
			_label.x = w+2;
			addChild(_label);
			if(_label.height>h) _label.y = (_label.height - h)/2;
			else _label.y = (h-_label.height)/2
		}

		override protected function dispose():void{
			super.dispose();
			unbindEvent();
		}
		
	}
}